package com.all.mqtt.controller;

import com.all.mqtt.consumer.MqttConsumerConfig;
import com.all.mqtt.provide.MqttProviderConfig;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

/**
 * @Author LY
 * @create 2024/3/1 16:14
 * @Description mqtt 消息发送
 */
@RestController
public class SendController {
    @Resource
    private MqttProviderConfig providerClient;
    @Resource
    private MqttConsumerConfig mqttConsumerConfig;

    @Value("${spring.mqtt.client.consumer_id}")
    private String clientId;

    @GetMapping("/providerConnect")
    public String providerConnect(){
        providerClient.connect();
        return "生产者连接到服务器";
    }

    @PostMapping("/sendMessage")
    public String sendMessage(int qos,boolean retained,String topic,String message){
        try {
            providerClient.publish(qos, retained, topic, message);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "发送失败";
        }
    }

    @GetMapping("/consumerConnect")
    public String consumerConnect(){
        mqttConsumerConfig.connect();
        return clientId + "消费者连接到服务器";
    }

    @GetMapping("/disConnect")
    public String disConnect(){
        mqttConsumerConfig.disConnect();
        return clientId + "与服务器断开连接";
    }

    @PostMapping("/subscribe")
    public String subscribe(String topic,int qos){
        mqttConsumerConfig.subscribe(topic,qos);
        return clientId + "与服务器订阅主题";
    }
}
